﻿using System;
using System.IO;
using System.Web;

using Infrastructure.Diagnostics;
using TempEmployees.Interfaces;
using TempEmployees.BLL.AnamReports;

namespace TempEmployees.WebServices
{
    public class ReportsSubmitterWebService : IReportsSubmitter
    {
        public bool SubmitReports(byte[] reports)
        {
            Logger.Info("Start submission");

            string reportPath = SaveToFile(reports);

            AnamReportsParser parser = new AnamReportsParser();
            parser.SubmitReport(reportPath);

            return true;
        }

        private string SaveToFile(byte[] reports)
        {
            string directory = Path.Combine(HttpContext.Current.Server.MapPath("~"), "AnamReports");
            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);

            string reportPath = Path.Combine(directory, string.Format("AnamReport__{0:dd-MM-yy__HH-mm-ss}.txt", DateTime.Now));
            using (MemoryStream ms = new MemoryStream(reports))
            using (FileStream fs = new FileStream(reportPath, FileMode.Create))
            {
                ms.WriteTo(fs);
            }
            return reportPath;
        }
    }
}
